import re
import os
import base64
from requests_oauthlib import OAuth1Session


class AuthInfo:
    """初始化 MAAS API 客户端"""

    def __init__(self, maas_url, api_key):
        self.maas_url = maas_url.rstrip("/") + "/"
        self.client_key, self.token_key, self.token_secret = api_key.split(":")
        self.session = self._auth_info()

    def _auth_info(self):
        return OAuth1Session(
            client_key=self.client_key,
            resource_owner_key=self.token_key,
            resource_owner_secret=self.token_secret,
        )


class BaseMachineInfo:
    """获取机器信息的基础类"""

    def __init__(self, session, maas_url, hosts):
        self.session = session
        self.hosts = self._format_hosts(hosts)
        self.maas_url = maas_url.rstrip("/") + "/"
        self.results = self.get_machine_info()

    def _format_hosts(self, hosts):
        """去重并保持顺序"""
        seen = set()
        return [m for m in re.split(r'[,\s]+', str(hosts).strip()) if m and not (m in seen or seen.add(m))]

    def get_machine_info(self):
        results = []
        for host in self.hosts:
            url = f"{self.maas_url}api/2.0/machines/?hostname={host}"
            resp = self.session.get(url)
            resp.raise_for_status()
            machine = resp.json()[0]
            results.append({
                "Hostname": machine.get("hostname"),
                "system_id": machine.get("system_id"),
                "status": machine.get("status_name", "")
            })
        return results


class BaseDeploy:
    """通用部署/操作类"""

    def __init__(self, maas_url, session, host):
        self.maas_url = maas_url.rstrip("/") + "/"
        self.session = session
        self.host = host

    def get_machine_info(self):
        url = f"{self.maas_url}api/2.0/machines/{self.host['system_id']}/"
        resp = self.session.get(url)
        resp.raise_for_status()
        machine = resp.json()
        return {
            "Hostname": machine.get("hostname"),
            "system_id": machine.get("system_id"),
            "status": machine.get("status_name", "")
        }

    def op_release(self):
        url = f"{self.maas_url}api/2.0/machines/{self.host['system_id']}/op-release"
        self.session.post(url)

    def op_commission(self):
        url = f"{self.maas_url}api/2.0/machines/{self.host['system_id']}/op-commission"
        self.session.post(url)


class OSDeploy(BaseDeploy):
    """操作系统部署"""

    def __init__(self, maas_url, session, host, distro_series, user_data):
        super().__init__(maas_url, session, host)
        self.distro_series = distro_series
        self.user_data = base64.b64encode(user_data.encode("utf-8")).decode("utf-8")

    def deploy(self):
        url = f"{self.maas_url}api/2.0/machines/{self.host['system_id']}/op-deploy"
        payload = {
            "distro_series": self.distro_series,
            "user_data": self.user_data
        }
        self.session.post(url, data=payload)
